package com.le.tester.imooc.oldfairy.jvm;

import com.github.javafaker.Faker;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.concurrent.ForkJoinPool;

/**
 * createTime：2023/6/27 14:08
 * description：WebOutOfMem
 */
public class WebOutOfMem {

    public static void main(String[] args) throws IOException {
        //thread pool
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        //Faker,test util
        Faker fakerUtil = new Faker();

        ArrayList<String> list = new ArrayList<>();

        //try-with-resource
        try (ServerSocket socket = new ServerSocket(8080)) {
            while (true) {
                Socket accept = socket.accept();
                forkJoinPool.submit(() -> {
                    String resp = "HTTP/1.1 200 ok\n\n";
                    try {

                        OutputStream opStream = accept.getOutputStream();
                        resp += fakerUtil.shakespeare().asYouLikeItQuote();
                        list.add(resp);

                        opStream.write(resp.getBytes(StandardCharsets.UTF_8));
                        opStream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            accept.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }
}